package com.rickpan.repository;

import com.rickpan.entity.VipSubscription;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.time.LocalDate;
import java.util.List;
import java.util.Optional;

/**
 * VIP订阅数据访问接口
 */
@Repository
public interface VipSubscriptionRepository extends JpaRepository<VipSubscription, Long> {

    /**
     * 根据用户ID查找订阅列表
     */
    List<VipSubscription> findByUserIdOrderByCreatedAtDesc(Long userId);

    /**
     * 根据用户ID和状态查找订阅
     */
    List<VipSubscription> findByUserIdAndStatus(Long userId, VipSubscription.SubscriptionStatus status);

    /**
     * 查找用户当前生效的订阅
     */
    @Query("SELECT v FROM VipSubscription v WHERE v.userId = :userId AND v.status = 'ACTIVE' AND v.endDate >= :currentDate ORDER BY v.endDate DESC")
    Optional<VipSubscription> findCurrentActiveSubscription(@Param("userId") Long userId, @Param("currentDate") LocalDate currentDate);

    /**
     * 查找即将过期的订阅 (7天内)
     */
    @Query("SELECT v FROM VipSubscription v WHERE v.status = 'ACTIVE' AND v.endDate BETWEEN :startDate AND :endDate")
    List<VipSubscription> findExpiringSubscriptions(@Param("startDate") LocalDate startDate, @Param("endDate") LocalDate endDate);

    /**
     * 查找已过期但状态未更新的订阅
     */
    @Query("SELECT v FROM VipSubscription v WHERE v.status = 'ACTIVE' AND v.endDate < :currentDate")
    List<VipSubscription> findExpiredActiveSubscriptions(@Param("currentDate") LocalDate currentDate);

    /**
     * 统计用户的订阅总数
     */
    @Query("SELECT COUNT(v) FROM VipSubscription v WHERE v.userId = :userId")
    Long countByUserId(@Param("userId") Long userId);

    /**
     * 查找订单关联的订阅
     */
    Optional<VipSubscription> findByOrderId(Long orderId);

    /**
     * 查找指定时间范围内创建的订阅
     */
    @Query("SELECT v FROM VipSubscription v WHERE v.createdAt BETWEEN :startDate AND :endDate")
    List<VipSubscription> findSubscriptionsBetween(@Param("startDate") LocalDate startDate, @Param("endDate") LocalDate endDate);

    /**
     * 统计活跃VIP用户数量
     */
    @Query("SELECT COUNT(DISTINCT v.userId) FROM VipSubscription v WHERE v.status = 'ACTIVE' AND v.endDate >= :currentDate")
    Long countActiveVipUsers(@Param("currentDate") LocalDate currentDate);
}